<?php

/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/8/28
 * Time: 14:55
 */
/**
 * 微信消息类，相当于index包里的weixin.class
 */
class WeixinModel {

    //微信公众号的配置信息，换完配置信息和模板调用号，还有config的回调配置，出现redirect_uri域名与后台配置不一致，修改网页账号的授权用户基本信息，单单用域名
    private $appid="wx7c29ba1e2db9305f";//wx7c29ba1e2db9305f
    private $appsecret="a20c14d68ac706b11ed8dfa67db6625e";//a20c14d68ac706b11ed8dfa67db6625e

    /**
     * http请求函数
     * @param array $data 要POST的数据
     */
    function http_request($url,$data=array()){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }


    /**
     * 获取access_token
     */
    private function getAccessToken(){
        $json_token=self::http_request("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$this->appid."&secret=".$this->appsecret);
        $access_token=My::arr2var(json_decode($json_token,true),'access_token');
        return $access_token;
    }


    /**
     * 发送模板消息
     * @param string $openid 用户的openid
     * @param string $template_id 模板id
     * @param array $data 模板参数
     * @param string $url ‘详情’链接
     */
    public function sendTplMsg($openid,$template_id,$data,$url=''){
        $access_token=self::getAccessToken();
        var_dump($openid);
        //模板消息
        $template=array(
            'touser'=>$openid,
            'template_id'=>$template_id,//模板ID
            'url'=>$url,//‘详情’链接
            //模板参数
            'data'=>$data
        );
        // $template=array(
        //         'touser'=>"oJIU40sAN3U0byTwgei320e15WjI",
        //         'template_id'=>"Q3OLPNc3iO_duQf9Dn4IMfIJyqb710jMkBhF-Xhve-4",
        //         'url'=>"",
        //         'data'=>array(
        //                 'project'=>array('value'=>"bigproject",'color'=>'#173177'),
        //                 'username'=>array('value'=>"who",'color'=>'#173177'),
        //                 'type'=>array('value'=>"2",'color'=>'#173177'),
        //                 'time'=>array('value'=>urlencode(date("Y年m月d日 H:i:s")),'color'=>'#173177'),
        //                 'result'=>array('value'=>"haoshi",'color'=>'#173177'),
        //                 'content'=>array('value'=>"nothing",'color'=>'#173177'),
        //             ),
        //     );
        $json_template=json_encode($template);
        var_dump($json_template);
        $json=urldecode($json_template);
        var_dump($json);
        $url="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$access_token;
        $res=self::http_request($url,urldecode($json_template));
        var_dump($res);
        exit();
        //发送成功
        if (My::arr2var(json_decode($res,true),'errcode')==0)
            return true;
        //发送失败
        else
            return false;

    }


    /**
     * 发送客服消息
     * @param string $openid 用户的openid
     * @param string $message 消息内容
     * @param string $kf_account 客服号
     */
    public function sendCsMsg($openid,$message,$kf_account=''){
        $access_token=self::getAccessToken();
        //客服消息
        $msg=array(
            'touser'=>$openid,
            'msgtype'=>"text",
            'text'=>array(
                'content'=>urlencode($message),
            )
        );
        //客服号
        if($kf_account)
            $msg['customservice'] = array("kf_account" => $kf_account);
        $json_msg=json_encode($msg);
        $url="https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$access_token;
        $res=self::http_request($url,urldecode($json_msg));
        //发送成功
        if (My::arr2var(json_decode($res,true),'errcode')==0)
            return true;
        //发送失败
        else
            return false;
    }



    /**
     * 查询UnionID
     * @param string $openid 微信用户的UnionID
     */
    public function getUnionID($openid){
        $access_token=self::getAccessToken();
        $json_info=self::http_request("https://api.weixin.qq.com/cgi-bin/user/info?access_token={$access_token}&openid={$openid}&lang=zh_CN");
        $unionid = My::arr2var(json_decode($json_info,true),'unionid');
        return $unionid;
    }


    /**
     * 更新Openid关系数据表
     */
    public function updateOpenidDb(){
        $access_token=self::getAccessToken();
        $openid_list = self::getOpenidList();
        if($openid_list){
            $querey_list = array();//需要查询的openid
            foreach($openid_list as &$value){
                $exist = DB('weixin_openid')->where("`openid`='{$value}'")->cache()->find();
                if(!$exist)
                    $querey_list[] = $value;
            }
            if($querey_list){
                $unionid_list = self::getUnionIDList($querey_list);
                if($unionid_list)
                    foreach($unionid_list as $key=>&$vvv){
                        DB('weixin_openid')->clear()->add(array('openid'=>$key,'unionid'=>$vvv));
                    }
            }
        }
    }


    /**
     * 获取关注用户Openid列表
     * @param string $next_openid 上一次调用得到的返回中的next_openid值(当关注者超过10000，需要递归调用该函数的时候，要用到这个参数)
     * @param array $result 返回结果
     */
    public function getOpenidList($next_openid='',$result=array()){
        $access_token=self::getAccessToken();
        //查询关注用户列表
        $url = "https://api.weixin.qq.com/cgi-bin/user/get?access_token={$access_token}";
        //当关注用户超过10000，再次查询时
        if($next_openid)
            $url.="&next_openid={$next_openid}";
        $json_user=self::http_request($url);
        $arr_user=json_decode($json_user,true);
        //关注用户openid
        $openid_list = My::arr2var($arr_user,'data.openid');
        if($openid_list)
            $result = array_merge($result,$openid_list);
        //返回结果中的next_openid值，该参数有值的话，说明关注用户超过10000，需要再次查询(一次只能返回10000个数据)
        $next_openid = My::arr2var($arr_user,'next_openid');
        if($next_openid)
            $result = self::getOpenidList($next_openid,$result);
        return $result;
    }


    /**
     * 批量查询UnionID
     * @param $array $openid_list openid列表
     * @param array $result 返回结果
     */
    public function getUnionIDList($openid_list,$result=array()){
        if(!$openid_list or !is_array($openid_list))
            return $result;
        $access_token=self::getAccessToken();
        //批量查询用户信息
        $url = "https://api.weixin.qq.com/cgi-bin/user/info/batchget?access_token={$access_token}";
        $user_list = array();
        //取前100个
        $openid_list_100 = array_slice($openid_list, 0, 100);
        foreach($openid_list_100 as &$vvv){
            $user_list[] = array('openid'=>$vvv,'lang'=>'zh-CN');
        }
        $post_data=array(
            'user_list'=>$user_list
        );
        $post_data=json_encode($post_data);
        $json_user=self::http_request($url,urldecode($post_data));
        $arr_user=My::arr2var(json_decode($json_user,true),'user_info_list');
        if($arr_user)
            foreach($arr_user as &$value){
                if(!empty($value['unionid']))
                    $result[$value['openid']] = $value['unionid'];
            }
        //当要查询的openid多于100个时
        if(count($openid_list)>100)
            $result = self::getUnionIDList(array_slice($openid_list, 100),$result);
        return $result;
    }



    /**
     * 获取客服聊天记录
     * @param int $start 开始时间戳
     * @param int $end 结束时间戳
     * @param int $page 页码
     * @param int $pagesize 每页条数
     * @param string $openid 微信用户openid(可选)
     */
    public function getRecord($start,$end,$page,$pagesize,$openid=''){
        $access_token=self::getAccessToken();;
        //post数据
        $post_data=array(
            "starttime" => strtotime($start),
            "endtime" => strtotime($end),
            "pageindex" => $page,
            "pagesize" => $pagesize,
            "openid" => $openid,
            //"openid" => 'oUIrxty4DP83u8uoSGj_lNJXT2Kc'
        );
        $json_template=json_encode($post_data);
        $url="https://api.weixin.qq.com/customservice/msgrecord/getrecord?access_token=".$access_token;
        $res=self::http_request($url,urldecode($json_template));
        $recordlist = My::arr2var(json_decode($res,true),'recordlist');
        return $recordlist;
    }


    /**
     * 操作代码转说明文字
     * @param int $code 操作代码
     */
    public function opercode2str($code){
        $oper_arr = array(
            '1000' => '创建未接入会话',
            '1001' => '接入会话',
            '1002' => '主动发起会话 ',
            '1003' => '转接会话',
            '1004' => '关闭会话',
            '1005' => '抢接会话',
            '2001' => '公众号收到消息',
            '2002' => '客服发送消息',
            '2003' => '客服收到消息'
        );
        if(isset($oper_arr[$code]))
            return $oper_arr[$code];
        else
            return "未知操作({$code})";
    }


    /**
     * 操作代码转文字颜色
     * @param int $code 操作代码
     */
    public function opercode2color($code){
        $oper_arr = array(
            '1000' => '#FF0000',
            '1001' => '#FF0000',
            '1002' => '#FF0000 ',
            '1003' => '#FF0000',
            '1004' => '#FF0000',
            '1005' => '#FF0000',
            '2001' => '#0000FF',
            '2002' => '#698B22',
            '2003' => '#0000FF'
        );
        if(isset($oper_arr[$code]))
            return $oper_arr[$code];
        else
            return "#000000";
    }

    /**
     * 微信信息推送
     * @param array $receiverIdArr  微信要通知的成员
     * @param array $task  微信推送的内容
     */
    public function sendWeixin($receiverIdArr,$task){
        $ids = My::implode(',', $receiverIdArr);
        if(!My::is_ids($ids)) return false;
        $receiver = DB('homeuser')->where("openid!='' AND id IN({$ids})")->field('openid,username')->cache()->select();
        if(!$receiver)
            return false;
        foreach ($receiver as $key => $value){
            $openid = $value['openid'];
            $data = array(
                'username'=>array('value'=>urlencode($value['username']),'color'=>"#666"),
                'type'=>array('value'=>urlencode($task['type']),'color'=>"#173177"),
                'project'=>array('value'=>urlencode($task['project']),'color'=>"#173177"),
                'result'=>array('value'=>urlencode($task['result']),'color'=>"#173177"),
                'time'=>array('value'=>urlencode(date("Y年m月d日 H:i:s")),'color'=>'#173177'),
            );
            $template_id = "q7JfLrBIJyqp8kVY-yox6FI-V9AjQ5uvGJQSg8rg9pE";//q7JfLrBIJyqp8kVY-yox6FI-V9AjQ5uvGJQSg8rg9pE
//            $url = "http://".$_SERVER ['HTTP_HOST'].__PROJECT__."task/detail/id-".My::arr2var($task,'id')."/";
            self::sendTplMsg($openid,$template_id,$data,'');
        }
    }

    /**
     * 微信信息推送
     * @param array $receiverId  微信要通知的成员
     * @param array $task  微信推送的内容
     */
    public function sendWeixin_one($receiverId,$task){
        if(!My::is_id($receiverId)) return false;
        $receiver = DB('homeuser')->where("openid!='' AND id =({$receiverId})")->field('openid,username')->cache()->find();
        if(!$receiver)
            return false;
        $openid = $receiver['openid'];
        $data = array(
            'username'=>array('value'=>urlencode($receiver['username']),'color'=>"#173177"),
            'project'=>array('value'=>urlencode($task['project']),'color'=>"#173177"),
            'type'=>array('value'=>urlencode($task['type']),'color'=>"#173177"),
            'result'=>array('value'=>urlencode($task['result']),'color'=>'#173177'),
            'time'=>array('value'=>urlencode(date("Y年m月d日 H:i:s")),'color'=>'#173177'),
            'content'=>array('value'=>urlencode($task['content']),'color'=>'#173177'),
        );
        $template_id = "qRVUP2QptyM2RAG8OuFujjtaF_MdtV1cq-rvW6FcPzk";//qRVUP2QptyM2RAG8OuFujjtaF_MdtV1cq-rvW6FcPzk
//        $url = "http://".$_SERVER ['HTTP_HOST'].__PROJECT__."task/detail/id-".My::arr2var($task,'id')."/";
        self::sendTplMsg($openid,$template_id,$data,'');
    }
}